<template>
  <div>
    <el-dialog
      title="预警配置"
      width="1200px"
      custom-class="config-option-list-dialog"
      :visible="visible && !formVisible"
      @close="handleClose"
    >
      <div>
        <div class="table-header">
          <el-button size="mini" type="primary" plain @click="showOption({})">
            新增规则
          </el-button>
          <el-button
            size="mini"
            type="danger"
            plain
            :disabled="selectedRows.length === 0"
            @click="deleteBySelected"
          >
            批量删除
          </el-button>
        </div>
        <el-table
          v-loading="loading.table"
          ref="table"
          :data="tableData"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" align="center"> </el-table-column>
          <el-table-column label="序号" type="index" width="50px">
          </el-table-column>
          <el-table-column
            prop="description"
            label="预警规则描述"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column prop="warningObjectName" label="预警对象">
          </el-table-column>
          <el-table-column prop="isUsed" width="88" label="是否启用">
            <template slot-scope="{ row }">
              <span :style="row.isUsed === '0' ? {} : { color: 'red' }">
                {{ row.isUsed === "0" ? "是" : "否" }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" width="160" label="修改时间">
          </el-table-column>
          <el-table-column label="操作" width="160px">
            <template slot-scope="{ row }">
              <div class="table-operation">
                <!-- <el-link type="primary" @click="toggleState(row)">
                  {{ row.isUsed === '0' ? '停用' : '启用' }}
                </el-link> -->
                <el-link type="primary" @click="showOption(row)">配置</el-link>
                <el-link type="danger" @click="deleteById(row.id)"
                  >删除</el-link
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
    <ConfigOption
      :visible="formVisible"
      :relation-id="relationId"
      :id="currentRecord.id"
      :field="field"
      @refresh="fetchTableData"
      @close="formVisible = false"
    />
  </div>
</template>

<script>
import ConfigOption from "./config-option";
export default {
  components: { ConfigOption },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    relationId: {
      type: String,
      default: "",
    },
    field: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      tableData: [],
      selectedRows: [],
      formVisible: false,
      currentRecord: {},
      loading: {
        table: false,
      },
    };
  },
  watch: {
    visible(newVisible) {
      if (newVisible) {
        this.tableData = [];
        this.fetchTableData();
      }
    },
  },
  methods: {
    fetchTableData() {
      const params = { id: this.relationId };
      this.loading.table = true;
      this.$http
        .get("/cgjybzWarningRules/getRulesList", { params })
        .then((res) => {
          this.tableData = res.data.data || [];
        })
        .finally(() => {
          this.loading.table = false;
        });
    },
    handleClose() {
      // 只有表单弹窗没打开的时候才允许关闭
      if (!this.formVisible) {
        this.$emit("close");
      }
    },
    deleteBySelected() {
      const ids = this.selectedRows.map((item) => item.id);
      this.$confirm(`确定要删除所选的 ${ids.length} 条记录吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        beforeClose: (action, instance, done) => {
          if (action === "confirm") {
            // 调用接口删除
            this.handleDelete(ids.join(",")).finally(done);
          } else {
            done();
          }
        },
      });
    },
    deleteById(id) {
      this.$confirm("确定要删除这条记录吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        beforeClose: (action, instance, done) => {
          if (action === "confirm") {
            // 调用接口删除
            this.handleDelete(id).finally(done);
          } else {
            done();
          }
        },
      });
    },
    handleDelete(idStr) {
      const params = { id: idStr };
      return this.$http
        .get("/cgjybzWarningRules/deleteRules", { params })
        .then((res) => {
          this.$message.success("删除成功");
          // 清空用户选项
          this.$refs.table.clearSelection();
          this.selectedRows = [];
          // 刷新表格数据
          this.fetchTableData();
        })
        .catch((e) => {
          this.$message.error("删除失败，请稍后再试");
          console.error("删除失败：", e);
        });
    },
    showOption(row) {
      this.currentRecord = row;
      this.formVisible = true;
    },
    toggleState(row) {},
    handleSelectionChange(val) {
      this.selectedRows = val;
    },
  },
};
</script>

<style lang="scss">
.config-option-list-dialog {
  .table-header {
    margin-bottom: 10px;
  }
  .table-operation {
    > * {
      margin-right: 16px;
    }
  }
}
</style>
